<template>
  <div class="app-container">
    <el-card class="edit-container" shadow="never">
      <template #header>
        <div class="header">
          <span>{{ isEdit ? '编辑文章' : '新增文章' }}</span>
          <div class="operations">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSaveDraft">保存草稿</el-button>
            <el-button type="success" @click="handlePublish">发布文章</el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>

        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 200px">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="封面图片" prop="coverImage">-->
<!--          <el-upload-->
<!--            class="cover-uploader"-->
<!--            :action="uploadAction"-->
<!--            :headers="uploadHeaders"-->
<!--            :show-file-list="false"-->
<!--            :before-upload="beforeUpload"-->
<!--            :on-success="handleCoverSuccess"-->
<!--          >-->
<!--            <img v-if="form.coverImage" :src="form.coverImage" class="cover-image">-->
<!--            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->

        <el-form-item label="文章内容" prop="content" class="editor-container">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px"
              v-model="form.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, shallowRef, onBeforeUnmount, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Plus } from '@element-plus/icons-vue'
import { getArticle, addArticle, updateArticle } from '@/api/article'
import { getCategoryList } from '@/api/articleCategory'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const isEdit = !!route.params.id

// 表单数据
const form = reactive({
  id: undefined,
  title: '',
  categoryId: undefined,
  coverImage: '',
  content: '',
  status: 0
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 编辑器配置
const editorRef = shallowRef()
const mode = 'default'
const toolbarConfig = {
  excludeKeys: [] // 可以配置需要排除的菜单项
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: import.meta.env.VITE_API_URL + '/api/upload/image',
      fieldName: 'file',
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      }
    }
  }
}

// 处理编辑器创建
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 上传相关配置
const uploadAction = import.meta.env.VITE_API_URL + '/api/upload/image'
const uploadHeaders = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 封面上传成功
const handleCoverSuccess = (res) => {
  form.coverImage = res.data
}

// 获取分类选项
const categoryOptions = ref([])
const getCategories = async () => {
  try {
    const res = await getCategoryList({ status: 1 })
    categoryOptions.value = res.data.records
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取文章详情
const getDetail = async () => {
  try {
    const res = await getArticle(route.params.id)
    console.error('获取文章ID:', res.data)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取文章详情失败:', error)
  }
}

// 保存文章
const saveArticle = async (status = 0) => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        form.status = status
        if (isEdit) {
          await updateArticle(form)
        } else {
          await addArticle(form)
        }
        ElMessage.success('保存成功')
        router.push('/article')
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 保存草稿
const handleSaveDraft = () => {
  saveArticle(0)
}

// 发布文章
const handlePublish = () => {
  ElMessageBox.confirm('确认要发布该文章吗?', '提示', {
    type: 'warning'
  }).then(() => {
    saveArticle(1)
  })
}

// 取消编辑
const handleCancel = () => {
  router.push('/article')
}

// 组件卸载前销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 初始化
onMounted(() => {
  getCategories()
  if (isEdit) {
    getDetail()
  }
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .edit-container {
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .operations {
        display: flex;
        gap: 10px;
      }
    }
  }

  .cover-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .cover-image {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
  }

  .editor-container {
    :deep(.w-e-text-container) {
      min-height: 500px;
    }
  }
}
</style>

<style>
.editor-container {
  z-index: 100;
}

.w-e-toolbar {
  z-index: 101;
}

.w-e-text-container {
  z-index: 100;
}

.w-e-full-screen-container {
  z-index: 2000;
}
</style>
